import React, { useState, useEffect, useCallback, useRef } from 'react';
import { ProColumns, ProTableProps } from '@ant-design/pro-table';
import { ProTable, MyProTableProps } from '@/components/KaiyaTable/index';
import {
  Modal,
  Tree,
  Input,
  Button,
  message,
  FormInstance,
  Select,
} from 'antd';
import { ExclamationCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { history } from 'umi';
import { ucEmployeePage, ucEmployeeDeleteId } from '@/services/deptControl';
import styles from './index.less';
import Const from '@/utils/Const';
import {
  getDepartmentTreeByRole,
  getJob,
  getOrgType,
  getPosition,
  getStatus,
  tileTreeNodes,
} from '@/pages/features/dept/help';
import { StatusEnum } from '@/pages/features/dept/staffEdit';

const { confirm } = Modal;
const UserManage: React.FC = () => {
  // 受控的ProForm
  const ref = useRef<FormInstance>();
  // 部门树
  const [departmentTree, setdepartmentTree] = useState([]);
  const [checkedKeys, setcheckedKeys] = useState([]);
  //岗位
  const [position, setPosition] = useState([]);
  //职务
  const [job, setJob] = useState([]);
  const [status, setStatus] = useState([]);

  const [checkedTitles, setcheckedTitles] = useState([]);
  const [treeModalVisible, settreeModalVisible] = useState<boolean | undefined>(
    false,
  );
  const TableCustomDeploy = {
    componentName: 'customTable',
  };
  useEffect(() => {
    //获取配置
    getSelectData();
  }, []);

  const getSelectData = async () => {
    // 获取部门树
    const department: any = await getDepartmentTreeByRole({
      orgType: getOrgType(),
    });
    setdepartmentTree(department);

    const job: any = await getJob();
    setJob(job);

    //岗位
    const position: any = await getPosition();
    setPosition(position);

    const status: any = await getStatus();
    setStatus(status);
  };

  // 删除
  const deleteOrganization = useCallback((id) => {
    confirm({
      title: '删除提示信息',
      icon: <ExclamationCircleOutlined />,
      content: '该操作将删除当前数据，确定删除吗？',
      async onOk() {
        const result = await ucEmployeeDeleteId(id);
        if (result.code === 200) {
          message.success('数据删除成功');
          console.log(ref);
          ref.current?.submit();
        }
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }, []);
  const getTableBasicDeploy = (): ProTableProps<any, any, any> => {
    const columns: ProColumns[] = [
      {
        dataIndex: 'condition',
        title: '模糊搜索',
        valueType: 'text',
        hideInTable: true,
        renderFormItem: (_, { defaultRender }) => {
          return <Input placeholder="人员姓名，工号，电话" />;
        },
      },

      {
        dataIndex: 'mgtScopeOrgIds',
        title: '机构筛选',
        valueType: 'text',
        hideInTable: true,
        renderFormItem: (_, { defaultRender }) => {
          return (
            <Input
              value={
                checkedTitles?.length > 0 ? checkedTitles.join('，') : '请选择'
              }
              onClick={() => {
                settreeModalVisible(true);
              }}
            />
          );
        },
      },

      {
        title: '序号',
        dataIndex: 'index',
        valueType: 'indexBorder',
        width: 48,
      },
      {
        dataIndex: 'name',
        title: '姓名',
        valueType: 'text',
        hideInSearch: true,
      },
      {
        title: '工号',
        dataIndex: 'jobNumber',
        valueType: 'text',
        hideInSearch: true,
      },
      {
        title: '性别',
        dataIndex: 'gender',
        valueType: 'text',
        hideInSearch: true,
        render: (text: any) => {
          return text === 1 ? '男' : '女';
        },
      },
      {
        title: '归属机构',
        dataIndex: 'belongToOrg',
        valueType: 'text',
        hideInSearch: true,
        render: (text: any) => {
          const nodes = tileTreeNodes(departmentTree);
          return nodes?.find((d: any) => d.id === text)?.name;
        },
      },
      {
        title: '职务',
        dataIndex: 'jobTitle',
        render: (text: any) => {
          return job?.find((d: any) => d.dictValue === text)?.dictLabel;
        },
        renderFormItem: () => {
          return (
            <Select>
              {job.map(
                (value: { dictValue: string; dictLabel: string }, index) => {
                  return (
                    <Select.Option key={index} value={value.dictValue}>
                      {value.dictLabel}
                    </Select.Option>
                  );
                },
              )}
            </Select>
          );
        },
      },
      {
        title: '岗位',
        dataIndex: 'jobPosition',
        render: (text: any) => {
          return position?.find((d: any) => d.dictValue === text)?.dictLabel;
        },
        renderFormItem: () => {
          return (
            <Select>
              {position.map(
                (value: { dictValue: string; dictLabel: string }, index) => {
                  return (
                    <Select.Option key={index} value={value.dictValue}>
                      {value.dictLabel}
                    </Select.Option>
                  );
                },
              )}
            </Select>
          );
        },
      },
      {
        title: '电话',
        dataIndex: 'phone',
        hideInSearch: true,
      },
      {
        title: '状态',
        dataIndex: 'status',
        render: (text: any) => {
          return status?.find((d: any) => d.dictValue === String(text))
            ?.dictLabel;
        },
        renderFormItem: () => {
          return (
            <Select>
              {status.map(
                (value: { dictValue: string; dictLabel: string }, index) => {
                  return (
                    <Select.Option key={index} value={value.dictValue}>
                      {value.dictLabel}
                    </Select.Option>
                  );
                },
              )}
            </Select>
          );
        },
      },
      {
        title: '操作',
        valueType: 'option',
        render: (text, record, _, action) => [
          <a
            href={record.url}
            target="_blank"
            rel="noopener noreferrer"
            key="view"
            onClick={() => {
              history.push({
                pathname: '/features/dept/staffEdit',
                state: {
                  id: record.id,
                  type: StatusEnum.DETAIL,
                },
              });
            }}
          >
            详情
          </a>,
          <a
            href={record.url}
            target="_blank"
            rel="noopener noreferrer"
            key="view"
            onClick={() => {
              history.push({
                pathname: '/features/dept/staffEdit',
                state: {
                  id: record.id,
                  type: StatusEnum.EDIT,
                },
              });
            }}
          >
            编辑
          </a>,
          <a
            href={record.url}
            target="_blank"
            rel="noopener noreferrer"
            key="view"
            onClick={() => deleteOrganization(record.id)}
          >
            删除
          </a>,
        ],
      },
    ];
    const rowSelection = {
      onChange: (selectedRowKeys: React.Key[], selectedRows: any[]) => {
        console.log(
          `selectedRowKeys: ${selectedRowKeys}`,
          'selectedRows: ',
          selectedRows,
        );
      },
      getCheckboxProps: (record: any) => ({
        disabled: record.name === 'Disabled User', // Column configuration not to be checked
        name: record.name,
      }),
    };
    return {
      columns,
      request: async (params = {}, sort, filter) => {
        let lastParams = {
          ...params,
          pageNumber: params.current,
        };
        delete lastParams.current;
        let res = await ucEmployeePage(lastParams);
        let resData = Const.dealResDataSwitch(res);
        return {
          data: resData.data,
          success: resData.code === 200,
          total: resData.total,
        };
      },
      onReset: () => {
        setcheckedTitles([]);
        setcheckedKeys([]);
        ref.current?.submit();
      },
      beforeSearchSubmit: (params: any) => {
        //提交表单之前对参数进行修改的操作
        if (checkedKeys.length) {
          return {
            ...params,
            mgtScopeOrgIds: checkedKeys,
          };
        }
        return params;
      },
      formRef: ref,
      rowSelection: {
        type: 'checkbox',
        ...rowSelection,
      },
      pagination: {
        pageSize: 5,
      },
      rowKey: 'id',
      toolBarRender: () => [
        // <Button icon={<FilterOutlined />}>查询</Button>,
        <Button
          icon={<PlusOutlined />}
          onClick={() => {
            history.push({
              pathname: '/features/dept/staffEdit',
              state: {
                type: StatusEnum.ADD,
              },
            });
          }}
        >
          新增
        </Button>,
        <Button
          icon={<PlusOutlined />}
          onClick={() => {
            history.push({
              pathname: '/features/dept/jobTransfer',
              state: {
                type: 'index',
              },
            });
          }}
        >
          人员批量调岗
        </Button>,
      ],
    };
  };
  const jsonOption: MyProTableProps = {
    TableCustomDeploy,
    TableBasicDeploy: getTableBasicDeploy,
  };
  return (
    <div className={styles.staffContainer}>
      <Modal
        title="组织架构"
        visible={treeModalVisible}
        onOk={() => {
          settreeModalVisible(false);
        }}
        onCancel={() => {
          setcheckedTitles([]);
          setcheckedKeys([]);
          settreeModalVisible(false);
        }}
        // style={{
        //   overflowY: 'auto',
        // }}
      >
        <Tree
          style={{ maxHeight: '50vh', overflowY: 'auto' }}
          checkable
          autoExpandParent={true}
          checkedKeys={checkedKeys}
          onCheck={(checkedKeysValue: any, checkedRow: any) => {
            let rowsByTitle = checkedRow.checkedNodes.map(
              (item: any) => item.title,
            );
            setcheckedTitles(rowsByTitle);
            setcheckedKeys(checkedKeysValue);
          }}
          treeData={departmentTree}
        />
      </Modal>

      <ProTable {...jsonOption}></ProTable>
    </div>
  );
};

export default UserManage;
